package com.cy.pj.sys.shiro;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

@Configuration
public class CORSConfiguration {

/*解决跨域问题*/
@Bean
public FilterRegistrationBean<CorsFilter> filterFilterRegistrationBean(){
    //1.对此过滤器进行配置(跨域设置-url,method)
    UrlBasedCorsConfigurationSource configSource=new UrlBasedCorsConfigurationSource();
    CorsConfiguration config=new CorsConfiguration();
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");//post,delete,get,put,....
    config.addAllowedOrigin("http://localhost:9000");
    config.setAllowCredentials(true);
    //2.注册过滤器并设置其优先级
    configSource.registerCorsConfiguration("/**", config);
    FilterRegistrationBean<CorsFilter> fBean=
            new FilterRegistrationBean(new CorsFilter(configSource));
    fBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return fBean;
}


    /*方案二*/
//    @Bean
//    public FilterRegistrationBean buildConfig() {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration corsConfiguration = new CorsConfiguration();
//        corsConfiguration.setAllowCredentials(true);
//        corsConfiguration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
//        corsConfiguration.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
//        corsConfiguration.setAllowedMethods(Collections.singletonList(CorsConfiguration.ALL));
//        corsConfiguration.addExposedHeader("Authorization");
//        source.registerCorsConfiguration("/**", corsConfiguration);
//        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
//        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
//
//        return bean;
//    }
}
